/*
 * To change this template, choose Tools | Templates and open the template in
 * the editor.
 */
package SteamEngineFX.Layouts;

import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.control.Button;
import javafx.scene.control.ToolBar;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.layout.VBox;

/**
 *
 * @author Jeff Bendixsen <jeff@westcoastcode.com>
 */
public class PropertiesPane extends VBox{
    
    private Parent root = null;
    
    private TreeView<String> tree = null;
    private ToolBar toolBar = null;
    
    public PropertiesPane(Parent rootNode){
        
        root = rootNode;
       
        Button btnRefresh = new Button("Refresh");
        btnRefresh.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent actionEvent) {
                refresh();
            }
        });
        
        toolBar = new ToolBar();
        toolBar.getItems().add(btnRefresh);
        
        getChildren().addAll(toolBar);
        
    }
    
    public void refresh(){

        getChildren().remove(tree);
        
        if (tree != null) tree = null;
        if (root == null) return;
        
        if (root != null){
            
            TreeItem<String> treeRoot = new TreeItem<String>(root.toString());
        
            reloadTree(root, treeRoot);
            tree = new TreeView<String>(treeRoot);
        }
        getChildren().add(tree);
    }
    
    private void reloadTree(Node node, TreeItem<String> treeRoot){
        
        if (node == null) return;
        if (node instanceof Parent){
            
            treeRoot.setValue(node.toString());
            loadChildren((Parent)node, treeRoot);
            
        }
    }
    
    private void loadChildren(Parent node, TreeItem<String> treeItem){
        
        for(int i = 0; i < node.getChildrenUnmodifiable().size(); i++){

            Node n = node.getChildrenUnmodifiable().get(i);

            TreeItem<String> newItem = new TreeItem<String>(n.toString());
            treeItem.getChildren().add(newItem);
            
            if (n instanceof Parent){
                loadChildren((Parent)n, newItem);
            }
        }
    }
    
}
